package com.rxy.annotation;

import com.rxy.factory.ProxyFactory;

import java.util.List;
import java.util.Map;

/**
 * 处理事务注解：@Transactional（待扩展属性）
 */
public class AnnotationTransactionHandler {

    /**
     * 为Service类生成代理对象
     * @param beanNameMap
     * @return
     */
    public static void handlerTransactionBean(Map<String, Class<?>> beanNameMap){
        for (Map.Entry<String, Class<?>> entry : beanNameMap.entrySet()) {
            Class<?> clazz = entry.getValue();
            String beanName = entry.getKey();
            //获取目标对象
            Object bean = AnnotationRigisterBean.getBean(beanName);
            //获取代理对象工厂类
            ProxyFactory proxyFactory = (ProxyFactory) AnnotationRigisterBean.getBean(ProxyFactory.class);
            Object proxy = null;
            //根据是否实现接口来生成代理对象
            if(bean.getClass().getInterfaces().length == 0){
                proxy = proxyFactory.getCglibProxy(bean);
            }else{
                clazz = clazz.getInterfaces()[0];
                proxy = proxyFactory.getJdkProxy(bean);
            }
            //将代理对象存入缓存池中
            AnnotationRigisterBean.getMap().put(beanName, proxy);
            AnnotationRigisterBean.getSingleTonObjects().put(clazz, proxy);
        }
    }
}
